var express = require('express');
var router = express.Router();
var moment = require('moment');
var fs = require('fs');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;

moment.locale('zh-cn');

function getRandomNum(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    return (Min + Math.round(Rand * Range));
}

var pad = function(tbl) {
    return function(num, n){
        n = n - (''+num).length;
        // console.log('asdasd=='+n);
        return (0 >= n) ? num : (tbl[n] || (tbl[n] = Array(n + 1).join(0)))+num;
    }    
}([]);

function createPomFile(repo, groupid, artifactid, version, resType, classifiers) {
    // 读取模板文件
    var pomTemplateFile = 'views/pom_template.xml';
    var data = fs.readFileSync(pomTemplateFile, "utf-8");
    // 替换其中的占位符
    data = data.replace('<%= groupId %>', groupid)
        .replace('<%= artifactId %>', artifactid)
        .replace('<%= version %>', version);
    var repoStr = '';
    if (repo != 'default') {
        repoStr = '<repositories>\n' +
            '	<repository>\n' +
            '		<id>custom</id>\n' +
            '		<url>' + repo + '</url>\n' +
            '	</repository>\n' +
            '</repositories>';
    }
    data = data.replace('<%= repos %>', repoStr);
    if (resType == 'any') {
        // 读取另一个灵活度更高的模板文件
        var pomTemplateFile2 = 'views/pom_template2.xml';
        var data2 = fs.readFileSync(pomTemplateFile2, "utf-8");
        var parentStr = repoStr + '\n' + '<dependencies>\n';
        for (var i = 0; i < classifiers.length; i++) {
            var str = '       <dependency>\n'+
                        '            <groupId>' + groupid + '</groupId>\n'+
                        '            <artifactId>' + artifactid + '</artifactId>\n'+
                        '            <version>' + version + '</version>\n';
            if (classifiers[i].length > 0) {
                str += '            <classifier>' + classifiers[i] + '</classifier>\n';
            }
            str += '        </dependency>\n';
            parentStr += str;
        }
        parentStr += '    </dependencies>';
        data = data2.replace('<%= dependencies %>', parentStr);
    } else if (resType == 'jar') {
        data = data.replace('<%= type %>', '');
    } else if (resType == 'java-source') {
        data = data.replace('<%= type %>', '<classifier>sources</classifier><type>java-source</type>');
    } else if (resType == 'test-jar') {
        data = data.replace('<%= type %>', '<classifier>tests</classifier><type>test-jar</type>');
    } else if (resType == 'pom') {
        data = data.replace('<%= type %>', '<type>pom</type>');
    } else {
        data = data.replace('<%= type %>', '<type>' + resType + '</type>');
    }
    // console.log('DEBUG=' + data);
    // 构造输出的临时文件的文件名
    var randNum = getRandomNum(0, 999999);
    var filePath = '/tmp/pom_' + randNum + '.xml';
    // 写文件
    fs.writeFileSync(filePath, data);

    return filePath;
}

function mvn_build_process(req, res, fileKey) {
    var fn = (function (error, stdout, stderr) {
        var msg = '';
        if (error !== null) {
            msg = '调用MAVEN编译时发生错误: <br/>' + (error + '').replace(/\n/g, '<br/>\n');
        } else if (stderr.length > 0) {
            msg = '调用MAVEN编译时发生错误: <br/>' + (stderr + '').replace(/\n/g, '<br/>\n');
        } else {
            msg = '<br/>'+
                stdout.replace(/\n/g, '<br/>\n') + '<br/><br/>'+
                '<a href="/download?id=' + fileKey + '">下载结果文件（一小时内有效）</a>';
        }
        res.render('upload', { title: '依赖提取工具(MAVEN版)', filekey: fileKey, message: msg });
    });
    return fn;
}

//单个依赖提取服务
router.post('/uploadsingle', function (req, res, next) {
    var repo = req.body.repo;
    var groupid = req.body.groupid;
    var artifactid = req.body.artifactid;
    var version = req.body.version;
    var resType = req.body.restype;
    var classifiers = req.body.classifier.toString().split(",");
    var otherclassifiers = req.body.otherclassifiers.split(",");
    var bIncludeOthers = false;
    var pos = 0;
    classifiers.forEach(classifier => {
        if (classifier == 'others') {
            bIncludeOthers = true;
        }
        if (!bIncludeOthers)
            pos++;
    });
    if (bIncludeOthers) {
        classifiers.splice(pos, 1);
        otherclassifiers.forEach(classifier => {
            classifiers.push(classifier);
        });
    }
    // classifiers.forEach(classifier => {
    //     console.log('==' + classifier);
    // });

    if (groupid && groupid.length > 0 && 
        artifactid && artifactid.length > 0) {
        // res.send('文件上传成功');
        // console.log(req.file);
        var filePath = createPomFile(repo, groupid, artifactid, version, resType, classifiers);
        console.log('收到一个请求：' + groupid + '.' + artifactid);

        var formatDate = moment().format('YYYYMMDDHHmmss'); /*格式化时间*/
        var randNum = getRandomNum(0, 999999);
        var fileKey = formatDate + '_' + pad(randNum, 6);
        // console.log('[DEBUG]==fileKey: ' + fileKey);

        (function(req, res, fileKey){
            // 执行命令
            var cmd = './bin/mvn_build ' + filePath + ' ' + fileKey;
            // console.log('[DEBUG]==CMD: ' + cmd);
            exec(cmd, mvn_build_process(req, res, fileKey));
        })(req, res, fileKey);
    } else {
        res.send('文件上传失败');
    }
});

router.process_async = function(req, callback, callback_err) {
    var repo = req.body.repo;
    var groupid = req.body.groupid;
    var artifactid = req.body.artifactid;
    var version = req.body.version;
    var resType = req.body.restype;
    var classifiers = req.body.classifier.toString().split(",");
    var otherclassifiers = req.body.otherclassifiers.split(",");
    var bIncludeOthers = false;
    var pos = 0;
    classifiers.forEach(classifier => {
        if (classifier == 'others') {
            bIncludeOthers = true;
        }
        if (!bIncludeOthers)
            pos++;
    });
    if (bIncludeOthers) {
        classifiers.splice(pos, 1);
        otherclassifiers.forEach(classifier => {
            classifiers.push(classifier);
        });
    }
    // classifiers.forEach(classifier => {
    //     console.log('==' + classifier);
    // });

    if (groupid && groupid.length > 0 && 
        artifactid && artifactid.length > 0) {
        var filePath = createPomFile(repo, groupid, artifactid, version, resType, classifiers);
        console.log('收到一个请求：' + groupid + '.' + artifactid);

        var formatDate = moment().format('YYYYMMDDHHmmss'); /*格式化时间*/
        var randNum = getRandomNum(0, 999999);
        var fileKey = formatDate + '_' + pad(randNum, 6);
        // console.log('[DEBUG]==fileKey: ' + fileKey);

        var child = spawn('./bin/mvn_build', [
            filePath, fileKey
        ]);

        child.stdout.on('data', callback);
        child.stderr.on('data', callback_err);

        // or if you want to send output elsewhere
        // child.stdout.pipe(dest);
        // (function(req, res, fileKey){
        //     // 执行命令
        //     var cmd = './bin/mvn_build ' + filePath + ' ' + fileKey;
        //     // console.log('[DEBUG]==CMD: ' + cmd);
        //     exec(cmd, mvn_build_process(req, res, fileKey));
        // })(req, res, fileKey);
    // } else {
    //     res.send('文件上传失败');
    }
};

module.exports = router;
